// 安装第三方库esphome/ESPAsyncWebServer-esphome
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <LittleFS.h>

AsyncWebServer server(80);

const char *ssid = "zhouweilei";
const char *password = "88637250";
const char *PARAM_MESSAGE = "message";

void notFound(AsyncWebServerRequest *request)
{
    request->send(404, "text/plain", "Not found");
}

void webroot(AsyncWebServerRequest *request)
{
    Serial.println("开始判断首页文件是否存在");
    // 检查SPIFFS文件系统中是否存在index.html文件
    if (LittleFS.exists("/index.html"))
    {
        fs::File file = LittleFS.open("/index.html", "r");
        { // 打开index.html
            if (file)
            {
                size_t fileSize = file.size(); // 获取文件大小
                String fileContent;

                // 逐字节读取文件内容
                while (file.available())
                {
                    fileContent += (char)file.read();
                }
                file.close(); // 关闭文件

                // 返回HTML内容
                Serial.println(fileContent);
                request->send(200, "text/html", fileContent);
                return;
            }
        }
    }
    // 如果文件不存在，返回404错误
    request->send(404, "text/plain", "Not found");
}

void websetting(AsyncWebServerRequest *request)
{
    Serial.println("开始判断首页文件是否存在");
    // 检查SPIFFS文件系统中是否存在index.html文件
    if (LittleFS.exists("/setting.html"))
    {
        fs::File file = LittleFS.open("/setting.html", "r");
        { // 打开index.html
            if (file)
            {
                size_t fileSize = file.size(); // 获取文件大小
                String fileContent;

                // 逐字节读取文件内容
                while (file.available())
                {
                    fileContent += (char)file.read();
                }
                file.close(); // 关闭文件

                // 返回HTML内容
                Serial.println(fileContent);
                request->send(200, "text/html", fileContent);
                return;
            }
        }
    }
    // 如果文件不存在，返回404错误
    request->send(404, "text/plain", "Not found");
}

void setup()
{

    Serial.begin(9600);
    LittleFS.begin();
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    if (WiFi.waitForConnectResult() != WL_CONNECTED)
    {
        Serial.printf("WiFi Failed!\n");
        return;
    }

    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());

    server.on("/", HTTP_GET, webroot);

    server.on("/setting.html", HTTP_GET, websetting);

    server.begin();
}

void loop()
{
}